<template>
	<view class="content">
		<view v-if="isBlueL && opacityL > 0.8" class="warningView warningViewL_b"></view>
		<view v-if="!isBlueL && opacityL > 0.8" class="warningView warningViewL_r"></view>

		<view v-if="isBlueR && opacityR > 0.8" class="warningView warningViewR_b"></view>
		<view v-if="!isBlueR && opacityR > 0.8" class="warningView warningViewR_r"></view>

		<view class="navView">
			<image src="../../../static/image/icon_left.png" mode="widthFix" @click="goBack()"></image>
			<text>深度监测</text>
			<view></view>
		</view>
		<view class="content brainView">
			<view v-if="isDeepStart">
				<image v-if="adornStateL" class="electrode_up_B elecAnimation"
					src="../../../static/image/detection/deep/icon_up_L_b.png" mode="widthFix"></image>
				<image v-else class="electrode_up_B elecAnimation"
					src="../../../static/image/detection/deep/icon_up_L_r.png" mode="widthFix"></image>

				<image v-if="adornStateL" class="electrode_down_B elecAnimation"
					src="../../../static/image/detection/deep/icon_down_L_b.png" mode="widthFix"></image>
				<image v-else class="electrode_down_B elecAnimation"
					src="../../../static/image/detection/deep/icon_down_L_r.png" mode="widthFix"></image>

				<image v-if="adornStateR" class="electrode_up_R elecAnimation"
					src="../../../static/image/detection/deep/icon_up_R_b.png" mode="widthFix"></image>
				<image v-else class="electrode_up_R elecAnimation"
					src="../../../static/image/detection/deep/icon_up_R_r.png" mode="widthFix"></image>

				<image v-if="adornStateR" class="electrode_down_R elecAnimation"
					src="../../../static/image/detection/deep/icon_down_R_b.png" mode="widthFix"></image>
				<image v-else class="electrode_down_R elecAnimation"
					src="../../../static/image/detection/deep/icon_down_R_r.png" mode="widthFix"></image>
			</view>


			<view class="brain_container">
				<image v-if="isBlueL" class="brain_L" :style="{opacity: opacityL}"
					src="../../../static/image/detection/deep/img_change_L_B.png" mode="widthFix"></image>
				<image v-else class="brain_L" :style="{opacity: opacityL}"
					src="../../../static/image/detection/deep/img_change_L_R.png" mode="widthFix"></image>

				<image v-if="isBlueR" class="brain_R" :style="{opacity: opacityR}"
					src="../../../static/image/detection/deep/img_change_R_B.png" mode="widthFix"></image>
				<image v-else class="brain_R" :style="{opacity: opacityR}"
					src="../../../static/image/detection/deep/img_change_R_R.png" mode="widthFix"></image>
			</view>
		</view>
		<view>
			<image style="width: 660rpx;" src="../../../static/image/detection/deep/img_body.png" mode="widthFix">
			</image>
		</view>
		<view class="countView">
			<view class="count_textView content">
				<text class="count">{{time}}</text>
				<text style="margin-top: 37rpx;">监测时请尽量保持安静状态</text>
			</view>
		</view>
		<!-- <view class="countView_shadow"></view> -->
		<view v-if="!isDeepStart" class="progressView">
			<ProgressBar :Width="percent" Type="aqua" :Vice="false"></ProgressBar>
		</view>
		<view v-else class="progressView">
			<view style="height: 38rpx;"></view>
		</view>
		<view class="monitorStatus" @click="changeMonitorStatus()">
			<image src="../../../static/image/detection/deep/stop.png" mode="widthFix"></image>
			<text v-text="monitorStatus"></text>
		</view>
		<!-- 和头环连接中断 -->
		<uni-popup ref="popup1" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_close" src="../../../static/image/icon_close.png" @click="closePopup()"></image>
				<image class="icon_content" src="../../../static/image/detection/icon_bluetooth.png"></image>
				<view class="content">
					<text class="popup1Content">连接失败</text>
					<text class="popup1Content">与头环连接中断</text>
				</view>
				<view class="popupBottomView content" @click="closePopup()"><text>我知道了</text></view>
			</view>
		</uni-popup>

		<!-- 是否需要退出 -->
		<uni-popup ref="popup2" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_content" src="../../../static/image/detection/icon_detection.png"></image>
				<view class="content">
					<text class="popup1Content">正在监测</text>
					<text class="popup1Content">请问是否需要退出</text>
				</view>
				<view class="popup_bottomView">
					<view class="popup_bottomViewitem content" style="border-radius:0 0 0 15px;background-color: #F5F5F5;" @click="cancel()">
						<text style="color: #333333;">取消</text>
					</view>
					<view class="popup_bottomViewitem content"
						style="background-color: #0659C7;border-radius:0 0 15px 0;" @click="enter()">
						<text style="color: #FFFFFF;">确定</text>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 触发了数据异常 -->
		<uni-popup ref="warnPopup" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_content" src="../../../static/image/iconPopup/icon_unusual.png"></image>
				<view class="content">
					<text class="popup1Content">数据监测异常</text>
					<text class="popup1Content">请确认电极是否贴合皮肤</text>
				</view>
				<view class="popup_bottomView">
					<view class="popup_bottomViewitem content" style="border-radius:0 0 0 15px;background-color: #F5F5F5;" @click="no()">
						<text style="color: #333333;">否</text>
					</view>
					<view class="popup_bottomViewitem content"
						style="background-color: #FF4d4d;border-radius:0 0 15px 0;" @click="yes()">
						<text style="color: #FFFFFF;">是({{notificationTimeTxt}})</text>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 是否通知紧急联系人 -->
		<uni-popup ref="notificationPopup" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1" style="height: 400rpx;">
				<text class="popup1Content" style="margin-top: 80rpx;">是否通知紧急联系人</text>
				<view class="popup_bottomView">
					<view class="popup_bottomViewitem content"
						style="border-radius:0 0 0 15px;background-color: #F5F5F5;" @click="Dontnotification()">
						<text style="color: #333333;">否</text>
					</view>
					<view class="popup_bottomViewitem content"
						style="background-color: #FF4d4d;border-radius:0 0 15px 0;" @click="notification()">
						<text style="color: #FFFFFF;">是({{notificationTimeTxt}})</text>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 头环未佩戴是否退出检测 -->
		<uni-popup ref="notWearingPopup" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<image class="icon_content" src="../../../static/image/iconPopup/icon_notWear.png"></image>
				<view class="content">
					<text class="popup1Content">检测到{{notWearingPosition==0?'左侧':'右侧'}}头环未佩戴</text>
					<text class="popup1Content">是否继续检测</text>
				</view>
				<view class="popup_bottomView">
					<view class="popup_bottomViewitem content" style="border-radius:0 0 0 15px;background-color: #F5F5F5;" @click="wetherDetection(false)"><text
							style="color: #333333;">取消</text></view>
					<view class="popup_bottomViewitem content"
						style="background-color: #0659C7;border-radius:0 0 15px 0;" @click="wetherDetection(true)">
						<text style="color: #FFFFFF;">确定</text>
					</view>
				</view>
			</view>
		</uni-popup>

		<annoyFree-popup ref="annoyPopup" :icon_src="icon_src" @btnEvent="btnEvent"></annoyFree-popup>
	</view>
</template>

<script>
	const app = getApp();
	import {
		process,
		evaluation,
		initVariable
	} from '../../../api/js/deepAlgorithm.js'
	import util from '../../../utils/utils.js';
	import * as api from '@/api/login';
	import {
		mapState
	} from 'vuex'; //引入mapState
	import ProgressBar from '@/components/Progress-Bar/Progress-Bar';
	// 定义变量...
	var impedanceL = new Array(); //左脑阻抗报文数组（120个字节长度）
	var impedanceR = new Array(); //右脑阻抗报文数组（120个字节长度）

	export default {
		data() {
			return {
				time: '00:00:00',
				monitorStatus: '暂停监测',
				notificationTimeTxt: '0', //通知时间倒计时
				notificationTime: null,
				percent: 0,
				adornStateL: true,
				adornStateR: true, //左右脑头环佩戴情况
				IntervalNumber: null, // 计时定时器
				countTime10: null, //弹窗倒计时10秒的定时器
				count: 0, //计时用的
				innerAudioContext: null,
				checkId: null,
				badWaveCount: 0, //坏波的个数 【0，1000】之外的情况
				icon_src: '',
				alreadyPopup: false, //断开弹窗是否已经显示
				bloodL: [], //左脑血流数据（500个float长度）
				bloodR: [], //右脑血流数据（500个float长度）
				bloodCount: 0, //计数器  ..判断数组是否组合完成 血流
				maxsize: 8407, //数组的最大长度
				regScore: 80, //REG分数
				leftAvg: [],
				rightAvg: [],
				frameBg_L: 0,
				frameBg_R: 0,
				isBlueL: true,
				isBlueR: true, //左右脑显示的图片颜色
				opacityL: 0,
				opacityR: 0,
				inputCount: 0, //录入数据的计数器
				isDeepStart: false,
				mappingRatio: '', //映射比
				deepWarningCount: 0, //深度监测告警计数器
				isCheckWavePass: true,
				resetFrame: {
					count: 0, //重置 参考帧的计数器
					leftTotal: 0,
					rightTotal: 0,
				},
				recvBuffer: [], // 用于接收蓝牙传输的全部数据
				notWearingPosition: 0,
				isFirstDeepMonitor: true,
			};
		},
		components: {
			ProgressBar
		},
		computed: {
			...mapState({
				isConnected: function(state) {
					return state.isConnected;
				}
			})
		},
		// 监听本地数据变化
		watch: {
			// 监听蓝牙连接状态
			isConnected: {
				handler(newValue, oldValue) {
					console.log(newValue);
					if (!newValue) {
						this.$refs.popup1.open('center');
						console.log('蓝牙断开连接了');
					}
				}
			}
		},
		onLoad() {
			console.log('onload');
			let that = this;
			this.$toast('请您调整手机音量', {
				icon: 'none'
			});
			plus.device.setWakelock(true);
			// 定义一个音频
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.autoplay = false;
			this.innerAudioContext.loop = false;
			let Timer = setTimeout(() => {
				clearTimeout(Timer)
				that.startMonitor()
			}, 1300)
			this.mappingRatio = Number(this.$store.state.mappingRatio)
		},
		// 监听页面卸载
		onUnload() {
      let that = this;
			console.log('onUnload');
			uni.$off('originalData',that.recvPackage);
			that.$store.commit('isLoopCheckAdornState', true);
			// 此处应该emit一个事件 ，如果 头环断开连接了，那么主页的弹窗就不用显示了
			uni.$emit('alreadyPopup', that.alreadyPopup);
			// 销毁音乐实例
			this.innerAudioContext.destroy();
		},
		methods: {
			// 开始检测
			startMonitor() {
				console.log('START');
				let that = this;
				uni.$on('originalData', that.recvPackage);
				initVariable()
				this.playAudio(this.$config.StaticUrl + '/audio/deepMonitor.mp3');
        setTimeout(() =>{
          app.writeBLEState(1)
        },800)

				this.showTimeIncrease();
				let t = setInterval(() => {
					if (that.percent < 98) {
						that.percent++
					} else if (that.percent == 98) {
						clearInterval(t)
					}
				}, 1000)
			},
			closePopup() {
				this.alreadyPopup = true;
				this.$refs.popup1.close();
				uni.switchTab({
					url: '../detection'
				});
			},
			/**
			 * 接收数据包 先组合成整包，而后在校验
			 * 1.根据0x68 获取后续完整报文 当接收到16时 开启校验（长度 crc）
			 */
			async recvPackage(event) {
				try {
					let array = Array.prototype.slice.call(new Uint8Array(event.msg));
					this.recvBuffer.push(...array)
					while (array.length >= 7) {
						let retVal = await this.checkPackage()
						if (retVal) {
							this.checkFormat(retVal)
						} else {
							break
						}
					}
				} catch (e) {
					console.log('checkPackage fail',e);
					//TODO handle the exception
				}
			},
			//组合成一个完整的数据
			checkPackage() {
				return new Promise((resolve) => {
					let buffer = this.recvBuffer
					for (let i = 0; i < buffer.length; i++) {
						if (buffer[i] === 0x68) {
							let lenBytes = [buffer[i + 1], buffer[i + 2]]
							let packLen = util.BytesToIntBigEndian(lenBytes)
							if (packLen <= buffer.length) {
								if (buffer[i + packLen - 1] === 0x16) {
									let _totalData = buffer.splice(i, packLen)
									return resolve(_totalData)
								}
							}
						}
					}
				})
			},
			//检查报文格式
			checkFormat(array) {
				if (array[0] === 0x68 && array[array.length - 1] === 0x16) {
					let crcContent = array.slice(1, -3)
					let crc16 = util.crc16_false(crcContent)
					if (array[array.length - 3] === crc16[0] && array[array.length - 2] === crc16[1]) {
						if (array[3] === 0x00) this.analyticDeepData(array);
						if (array[3] === 0x01 || array[3] === 0x02) this.analyticFastData(array);
					}
				}
			},
			//头环端 检测基础阻抗异常
			checkBaseWaveException(flag){
				app.writeBLEState(26)
				console.log(`${flag} 侧 头环脱离皮肤 ，请戴好`);
				this.$refs.notWearingPopup.open('center')
				let _src = ''
				if(flag) {
					this.adornStateL = false
					this.notWearingPosition = 0
					_src = this.$config.StaticUrl + '/audio/fastMonitorTips/notWearingL.mp3'
				} else {
					this.adornStateR = false
					this.notWearingPosition = 1
					_src = this.$config.StaticUrl + '/audio/fastMonitorTips/notWearingR.mp3'
				}
				let innerAudio = uni.createInnerAudioContext();
				innerAudio.src = _src
				innerAudio.play();
				let t = setTimeout(() => {
					clearTimeout(t)
					innerAudio.destroy()
				}, 5000)
			},
			// 是否继续检测 操作
			wetherDetection(flag){
				this.$refs.notWearingPopup.close()
				if(flag) {
          if (this.notWearingPosition === 0) {
            console.log("确定按钮")
            app.writeBLEState(1)
            this.bloodL = [];
            this.bloodR = [];
            setTimeout(() =>{
              this.adornStateL = true
            },800)

          } else {
            app.writeBLEState(25)
            let t2 = setTimeout(()=>{
              clearTimeout(t2)
              app.writeBLEState(24)
            },800)
            this.adornStateR = true
          }
				} else {
          app.writeBLEState(2)
          app.writeBLEState(26)
          uni.switchTab({
            url: '/pages/detection/detection'
          });
				}
			},
			//解析深度数据
			analyticDeepData(array) {
				console.log('深度 报文--: ', array.length)
				let decode_front = array.slice(4, -3)
				let decode_later = util.Data_Decrypt(decode_front, decode_front.length)
				let fixL = util.convertFloat(decode_later.slice(0, 4).reverse()).toFixed(2)
				let fixR = util.convertFloat(decode_later.slice(4, 8).reverse()).toFixed(2)
				this.adornStateL = (fixL < 1000 && fixL > 0)
				this.adornStateR = (fixR < 1000 && fixR > 0)
				if ((fixL > 1000 || fixL < 0) || (fixR > 1000 || fixR < 0)) {
					this.badWaveCount++;
				} else {
					this.badWaveCount = 0
					impedanceL.push(fixL)
					impedanceR.push(fixR)
					// 将数据录入算法包
					let obj = {
						left: fixL,
						right: fixR
					};
					let out = process(obj)
					console.log('out: ', out.allState);
					let resetTime = 100;  //TODO:  重置参考帧 时间,需要注意调试。。。
					if (this.count >= resetTime) this.brainGraphics(out.left, out.right)
					if (out.allState >= 60) {
						let modelData = new Object()
						modelData.impRange = 40.0
						let score = evaluation(out.leftOffset, out.rightOffset, this.regScore, modelData)
						console.log('告警score: ', score); //根据分数判断预警
						if (score < 60) {
							this.deepWarningCount++
							if (this.deepWarningCount > this.$store.state.deepWarningTimes) {
								this.toWarning()
							}
						} else {
							this.deepWarningCount = 0
						}
						//3分钟后重设背景帧
						if (this.count >= resetTime - 10) {
							if (this.resetFrame.count < 10) {
								this.resetFrame.count++
								this.resetFrame.leftTotal += out.left
								this.resetFrame.rightTotal += out.right
							} else if (this.resetFrame.count == 10) {
								console.log(`重置背景帧 L>${this.resetFrame.leftTotal} R>${this.resetFrame.rightTotal}`);
								this.frameBg_L = this.resetFrame.leftTotal / 10
								this.frameBg_R = this.resetFrame.rightTotal / 10
								this.resetFrame.count++
								if(this.isFirstDeepMonitor)  this.createDeepMonitor();
							}
						}
					}
					if (this.badWaveCount >= 5) {
						this.$toast('请确认佩戴好头环')
						this.badWaveCount = 0;
					}

          console.log("impedanceL",impedanceL.length)
					// 将数据发送到服务器
					if (impedanceL.length == 60 && impedanceR.length == 60) {
            console.log("impedanceL60零零零零")
              this.SendMsg2Server();

					}
				}

			},
			analyticFastData(array) {
				console.log('快速报文 : ', array[3])
				let decode_front = array.slice(4, -3)
				let decode_later = util.Data_Decrypt(decode_front, decode_front.length)
				let isLeft = array[3] === 0x01;
				let unableCount = 0,
					checkWaveData = [];
				for (let i = 0; i < 2100; i++) {
					let bdata = util.convertFloat(decode_later.slice(i * 4, i * 4 + 4).reverse());
					checkWaveData.push(bdata)
					if (bdata > 1000 || bdata < 0) unableCount++;
				}
				if (unableCount >= 125) {
					unableCount = 0
					this.$toast('请佩戴好头环')
					this.checkBaseWaveException(isLeft)
				}
				try {
					this.checkWave(checkWaveData)
					if (isLeft) this.bloodL.push(...checkWaveData)
					if (!isLeft) this.bloodR.push(...checkWaveData)
					if (this.bloodL.length === 2100 && this.bloodR.length === 2100) {
            setTimeout(() =>{
              app.writeBLEState(2)
            },800)
						if (this.isCheckWavePass) {
							if (!this.$store.state.isBuildModel) this.createUserModel(this.bloodL, this.bloodR)
							this.currentRegEvaluation(this.bloodL, this.bloodR);
							this.initData(this.bloodL, this.bloodR)
						}
						let t = setTimeout(() => {
              // debug 2024-10-14
							this.isDeepStart = true
              app.writeBLEState(3)
							clearTimeout(t)
						}, 2000)
						this.bloodL = []
						this.bloodR = []
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			toWarning() {
				// 触发紧急情况
				app.writeBLEState(26);
				let t = setTimeout(() => {
					clearTimeout(t)
					app.writeBLEState(2);
				}, 500)
				this.$refs.warnPopup.open('center');
				this.playAudio(this.$config.StaticUrl + '/audio/deepMonitorTips/warn.mp3');
				let notTime = 15;
				this.notificationTime = setInterval(() => {
					notTime--;
					this.notificationTimeTxt = notTime + 'S';
					if (notTime == 0) {
						this.deepWarning();
					}
				}, 1000);
			},
			//  左右脑图像处理
			brainGraphics(left, right) {
				let rate = this.mappingRatio
				console.log(`>>${this.frameBg_L}-- ${left}`);
				console.log(`..${this.frameBg_R}-- ${right}`);
				this.isBlueL = left - this.frameBg_L >= 0 ? true : false
				let diffL = Math.abs(left - this.frameBg_L)
				this.opacityL = 0.1 * (diffL / rate)

				this.isBlueR = right - this.frameBg_R >= 0 ? true : false
				let diffR = Math.abs(right - this.frameBg_R)
				this.opacityR = 0.1 * (diffR / rate)
			},
			//检查波形质量
			checkWave(wave) {
				let that = this
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId,
					action: 'checkWave',
					params: {
						wave,
						frequency: 50
					}
				};
				api.checkWave(data).then(function(res) {
					console.log('checkWave success', res);
					let waveQuality = res.data.data.waveQuality
					if (waveQuality < 0.2) that.isCheckWavePass = false
				}).catch(function(error) {
					console.log('checkWave fail', error);
				});
			},
			createUserModel(leftWave, rightWave) {
				let that = this
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId,
					action: 'createUserModel',
					params: {
						left: leftWave,
						right: rightWave
					}
				};
				api.createUserModel(data).then(function(res) {
					console.log('createUserModel success', res);
					that.$store.commit('isBuildModel', res.data.success)
				}).catch(function(error) {
					console.log('createUserModel fail', error);
				});
			},
			//获取当前REG分数
			currentRegEvaluation(left, right) {
				let that = this
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId,
					params: {
						left: [left],
						right: [right]
					}
				};
				api.currentRegEvaluation(data).then(function(res) {
					console.log('currentRegEvaluation success', res);
					if (res.data.success) {
						that.percent = 100
						if (that.isCheckWavePass) {
							that.regScore = res.data.data.regScore
						}
					}
				}).catch(function(error) {
					console.log('currentRegEvaluation fail', error);
					reject(false)
				});
			},
			initData(left, right) {
				let that = this
				// 获取到返回值后，控制头环停止采集，发送深度开始的指令 将两组数据每隔50点取平均值
				let leftAvg = [],
					rightAvg = [];
				let _left = 0,
					_right = 0;
				for (var i = 0; i < left.length; i++) {
					_left += left[i]
					_right += right[i]
					if ((i + 1) % 50 == 0) {
						leftAvg.push(parseFloat(_left / 50))
						rightAvg.push(parseFloat(_right / 50))
						_left = 0
						_right = 0
					}
				}
				that.leftAvg = leftAvg
				that.rightAvg = rightAvg
				let t = setInterval(() => {
					let obj = {
						left: leftAvg[that.inputCount],
						right: rightAvg[that.inputCount]
					};
					let out = process(obj)
					console.log('front out:--- ', out);
					that.inputCount++
					if (that.inputCount >= 42) {
						clearInterval(t)
					}
				}, 100)
			},
			playAudio(src) {
				this.innerAudioContext.src = src;
				this.innerAudioContext.play();
			},
			// 弹窗点击事件(暂停监测的按钮)
			btnEvent(e) {
				// 此处要做一些状态的清理
				this.clearState();
			},
			/* 清理各种状态
			 *  >> 关闭弹窗 >> 回到未检测的圆形页面
			 *  >> 清理数组数据
			 *  >> 清理定时器 （计时用的） （10秒倒计时用的）
			 *  >> 关闭音乐
			 */
			clearState() {
				this.$refs.annoyPopup.closePopup();
				this.resetData();
				this.innerAudioContext.stop();
				clearTimeout(this.countTime10);
				clearInterval(this.IntervalNumber);
				this.time = '00:00:00';
				this.count = 0;
			},
			showTimeIncrease() {
				//正计时
				var that = this;
				that.IntervalNumber = setInterval(() => {
					let count = that.count;
					let hou = parseInt(count / 60 / 60);
					let min = parseInt((count / 60) % 60);
					let sec = parseInt(count % 60);
					that.time = that.toDouble(hou) + ':' + that.toDouble(min) + ':' + that.toDouble(sec);
					that.count++;
				}, 1000);
			},
			toDouble(num) {
				return num < 10 ? '0' + num : '' + num
			},
			//开始创建深度监测任务
			createDeepMonitor(){
        console.log("开始创建深度监测任务")
				let that = this
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId,
					action: 'createDeepMonitor',
					params: {
						leftBaseImp: this.leftAvg,
						rightBaseImp: this.rightAvg,
						regScore: this.regScore,
						leftBack: this.frameBg_L,
						rightBack: this.frameBg_R,
						beginTime: this.$utils.getDateYYYYMMddHHMMSS()
					}
				};

        console.log("create",data)
				api.createDeepMonitor(data).then(function(res) {
					console.log('createDeepMonitor success', res)
					that.checkId = res.data.data.checkId
					that.isFirstDeepMonitor = false
          that.SendMsg2Server()
				}).catch(function(error) {
					console.log('createDeepMonitor fail', error);
				});
			},
			// 发送消息给服务器
			SendMsg2Server() {
        console.log("发数据给服务器")
        console.log("checkId",this.checkId)
        if(this.checkId === null && false) return;
				let that = this;
				let userId = this.$store.state.userInfo.currentUser.userId;
				let checkId = this.checkId;
				let leftBaseImp = impedanceL,
					rightBaseImp = impedanceR;
				let data = {
					userId: userId,
					action: 'deepMonitor',
					params: {
						checkId,
						userId,
						leftBaseImp,
						rightBaseImp
					}
				};
        console.log('deepMonitor data123123', data)
				api.deepMonitor(data).then(function(res) {
					console.log('深度 res success', res);
          impedanceL = [];
          impedanceR = [];
					if (res.data.code == 2000) {
						if (res.data.message == "操作成功！") {
							that.checkId = res.data.data.checkId;
						}
					}
				}).catch(function(error) {
					console.log('fastCheck fail', error);
				});
			},
			//完成监测任务
			completeDeepMonitor(){
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId,
					action: '',
					params: this.checkId
				};
				api.completeDeepMonitor(data).then(function(res) {
					console.log('completeDeepMonitor success', res);
				}).catch(function(error) {
					console.log('completeDeepMonitor fail', error);
				});
			},
			// 重新开始监测
			reStart() {
				impedanceL = []
				impedanceR = []
				app.writeBLEState(3);
			},
			// 未贴合皮肤，回到主页
			no() {
				clearInterval(this.notificationTime);
				this.$refs.warnPopup.close();
				this.enter();
			},
			// 确认贴合皮肤 跳转到二次确认是否通知紧急联系人
			yes() {
				let that = this;
				clearInterval(this.notificationTime);
				this.$refs.warnPopup.close()
				this.$refs.notificationPopup.open('center')
				let notTime = 15;
				that.notificationTime = setInterval(() => {
					notTime--;
					that.notificationTimeTxt = notTime + 'S';
					if (notTime == 0) {
						that.deepWarning();
					}
				}, 1000);
			},
			//不通知紧急联系人
			Dontnotification() {
				clearInterval(this.notificationTime);
				this.$refs.notificationPopup.close()
				this.enter();
			},
			// 通知紧急联系人
			notification() {
				clearInterval(this.notificationTime);
				this.$refs.notificationPopup.close()
				this.deepWarning();
			},
			deepWarning() {
				let that = this;
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId: userId,
					action: 'deepWarning',
				};
				api.deepWarning(data).then(function(res) {
					console.log('deepWarning success', res);
					if (res.data.code == 2000) {
						clearInterval(that.notificationTime);
						that.$toast('已启动预警服务')
						that.enter();
					}
				}).catch(function(error) {
					console.log('deepWarning fail', error);
				});
			},
			// 暂停 / 开始
			changeMonitorStatus: function() {
				if (this.monitorStatus == '暂停监测') {
					app.writeBLEState(26);
					let t = setTimeout(() => {
						clearTimeout(t)
						app.writeBLEState(2);
					}, 500)
					// 停止计时
					clearInterval(this.IntervalNumber);
					this.innerAudioContext.pause();
					this.monitorStatus = '开始监测';
				} else {
					app.writeBLEState(3);
					this.showTimeIncrease();
					this.monitorStatus = '暂停监测';
					this.innerAudioContext.play();
				}
			},
			// 取消tuichu
			cancel() {
				this.$refs.popup2.close();
			},
			// 监听返回按钮的触发
			onBackPress(options) {
				let that = this;
				that.$refs.popup2.open('center');
				return true;
			},
			goBack() {
				this.$refs.popup2.open('center');
				return true;
			},
			enter() {
        let that = this;
        // 关闭蓝牙
        app.writeBLEState(2)
        app.writeBLEState(26)
        that.clearState();
        if(!that.isFirstDeepMonitor){
          that.completeDeepMonitor()
        }
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/detection/detection'
          });
        }, 1000)
			},
			resetData() {
				console.log('清除所有数据！');
				// uni.$off('originalData');
				// 重置变量...
				impedanceL = new Array(); //左脑阻抗报文数组（120个字节长度）
				impedanceR = new Array(); //右脑阻抗报文数组（120个字节长度）
			},
		}
	};
</script>

<style>
	page {
		position: relative;
		width: 100vw;
		height: 100vh;
	}

	.navView {
		margin: 105rpx 0 0;
		width: 690rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.navView image {
		width: 38rpx;
	}

	.navView text {
		font-size: 34rpx;
		font-weight: bold;
		color: #333333;
	}

	.warningView {
		position: absolute;
		top: 0;
		width: 150rpx;
		height: 100%;
		animation: sharks 1.5s linear infinite;
	}

	@keyframes sharks {
		0% {
			opacity: 0.1;
		}

		50% {
			opacity: 1;
		}

		100% {
			opacity: 0.1;
		}

	}

	.warningViewL_r {
		left: 0;
		background: linear-gradient(to right, RGBA(219, 126, 126, 1), RGBA(219, 126, 126, 0));
	}

	.warningViewL_b {
		left: 0;
		background: linear-gradient(to right, RGBA(123, 171, 226, 1), RGBA(123, 171, 226, 0));
	}

	.warningViewR_r {
		right: 0;
		background: linear-gradient(to left, RGBA(219, 126, 126, 1), RGBA(219, 126, 126, 0));
	}

	.warningViewR_b {
		right: 0;
		background: linear-gradient(to left, RGBA(123, 171, 226, 1), RGBA(123, 171, 226, 0));
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	:root {
		--margin_border: 0rpx;
	}

	.brainView {
		margin-top: 50rpx;
		width: 281rpx;
		height: 331rpx;
		position: relative;
		background-image: url('../../../static/image/detection/deep/img_head.png');
		background-size: 100% 100%;
		justify-content: flex-start;
	}

	.elecAnimation {
		animation: elecSharks 3s infinite;
	}

	@keyframes elecSharks {
		0% {
			transform: scale(1, 1);
		}

		10% {
			transform: scale(0.9, 0.9);
		}

		20% {
			transform: scale(0.8, 0.8);
		}

		30% {
			transform: scale(0.7, 0.7);
		}

		40% {
			transform: scale(0.6, 0.6);
		}

		50% {
			transform: scale(0.5, 0.5);
		}

		60% {
			transform: scale(0.6, 0.6);
		}

		70% {
			transform: scale(0.8, 0.8);
		}

		80% {
			transform: scale(0.9, 0.9);
		}

		90% {
			transform: scale(0.9, 0.9);
		}

		100% {
			transform: scale(1, 1);
		}
	}

	.electrode_up_B {
		position: absolute;
		top: 90rpx;
		left: var(--margin_border);
		width: 18rpx;
	}

	.electrode_up_R {
		position: absolute;
		top: 90rpx;
		right: var(--margin_border);
		width: 18rpx;
	}

	.electrode_down_B {
		position: absolute;
		bottom: 32rpx;
		left: var(--margin_border);
		width: 27rpx;
	}

	.electrode_down_R {
		position: absolute;
		bottom: 32rpx;
		right: var(--margin_border);
		width: 27rpx;
	}

	.brain_container {
		margin-top: 27rpx;
		position: relative;
		width: 178rpx;
		height: 178rpx;
		background-image: url('../../../static/image/detection/deep/img_brain.png');
		background-size: 100% 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.brain_container image {
		width: 82rpx;
		position: absolute;
	}

	.brain_L {
		left: 13rpx;
	}

	.brain_R {
		right: 12rpx;
	}

	.countView {
		--border-width: 20rpx;
		position: relative;
		margin-top: 80rpx;
		width: 610rpx;
		height: 180rpx;
		border-radius: 50%;
		/* border: 15rpx solid #035FC8; */
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* .countView_after {
		width: 90%;
		height: 90%;
		background: #ffffff;
		border-radius: 50%;
	}
	.countView::before{
		content: "";
		position: absolute;
		width: 30rpx;
		background: linear-gradient(to left,RGBA(4, 235, 248, 1),RGBA(4, 235, 248, 0));
		height: 610rpx;
		animation: rotBGimg 3s linear infinite;
		transition: all 0.2s linear;
	}
	@keyframes rotBGimg {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	} */
	/* .countView::after {
		content: " ";
		position: absolute;
		background: #ffffff;
		inset: 10rpx;
		border-radius: 50%;
	} */

	.countView::after {
		position: absolute;
		content: "";
		top: calc(-1 * var(--border-width));
		left: calc(-1 * var(--border-width));
		z-index: -1;
		width: calc(100% + var(--border-width) * 2);
		height: calc(100% + var(--border-width) * 2);
		background: linear-gradient(60deg, #0373D9, #0360C9, #5ff2f0 10%, #0373D9, #0373D9);
		background-size: 300% 300%;
		background-position: 0 50%;
		border-radius: 50%;
		animation: moveGradient 6s alternate infinite;
	}

	@keyframes moveGradient {
		50% {
			background-position: 100% 50%;
		}
	}


	.countView_shadow {
		margin-top: -150rpx;
		width: 610rpx;
		height: 180rpx;
		z-index: -2;
		border-radius: 50%;
		border: 12rpx solid rgba(0, 0, 0, 0.1);
		box-shadow: 0 0 50rpx 5rpx rgba(0, 0, 0, 0.1);
	}

	.progressView {
		margin-top: 50rpx;
		width: 600rpx;
	}

	.count_textView {
		margin-top: -50rpx;
		z-index: 99;
		width: 350rpx;
		background-color: #FFFFFF;

	}

	.count_textView text:nth-child(1) {
		font-size: 66rpx;
		font-weight: bold;
		color: #035FC8;
	}

	.count_textView text:nth-child(2) {
		font-size: 26rpx;
		color: #035FC8;
		opacity: 0.75;
	}

	.count {
		font-size: 80rpx;
		font-family: Roboto;
		font-weight: bold;
		color: #035FC8;
	}

	.monitorStatus {
		margin: 50rpx 0;
		width: 645rpx;
		height: 82rpx;
		background-color: #0659c7;
		border-radius: 50px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.monitorStatus text {
		margin-left: 25rpx;
		font-size: 45rpx;
		color: #ffffff;
	}

	.monitorStatus image {
		width: 35rpx;
	}

	/* 弹出层 */
	.popup1 {
		width: 620rpx;
		height: 750rpx;
		background-color: white;
		border-radius: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}

	.icon_content {
		margin-top: 93rpx;
		width: 238rpx;
		height: 238rpx;
	}

	.popup1Content {
		margin-top: 20rpx;
		font-size: 52rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #333333;
	}

	.icon_close {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		top: 26rpx;
		right: 35rpx;
	}

	.popupBottomView {
		margin-bottom: 0rpx;
		width: 100%;
		height: 120rpx;
		border-radius: 0 0 15px 15px;
		background-color: #0659c7;
	}

	.popupBottomView text {
		font-size: 44rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #ffffff;
	}

	/* popup 底部两个按钮区域 */
	.popup_bottomView {
		width: 100%;
		height: 137rpx;
		border-top: #333333;
		/* border: 1px #323233 solid; */
		border-radius: 0 0 15px 15px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.popup_bottomViewitem {
		width: 50%;
		height: 100%;
		font-size: 44rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
	}
</style>